package file_controller

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "上传失败",
		})
		return
	}

	currentMillis := time.Now().UnixMilli()
	timeStr := fmt.Sprintf("%d", currentMillis)

	// 保存到指定目录
	dst := "./public/" + timeStr + "-" + file.Filename
	saveErr := c.SaveUploadedFile(file, dst)
	if saveErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "保存失败",
		})
		return
	}

	url := "http://localhost:9000/static/" + file.Filename
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "上传成功",
		"url":     url,
	})
}
